<template>
  <view class="job-edit-container">
    <!-- 顶部导航栏 -->
    <view class="top-bar">
      <view class="back-btn" @click="handleBack">
        <image src="/static/jiantou2_1.png" mode="aspectFit" class="back-icon"></image>
      </view>
      <text class="title">{{ isEditMode ? '编辑岗位' : '添加岗位' }}</text>
      <view class="right-space"></view>
    </view>
    
    <!-- 表单内容 -->
    <view class="form-container">
      <!-- 岗位名称 -->
      <view class="form-group">
        <text class="label">岗位名称 <text class="required">*</text></text>
        <input 
          type="text" 
          v-model="formData.name" 
          placeholder="请输入岗位名称" 
          class="input-field" 
        />
      </view>
      
      <!-- 所属上级岗位 -->
      <view class="form-group">
        <text class="label">所属上级岗位</text>
        <view class="picker-field" @click="showJobPicker = true">
          <text class="picker-display">{{ selectedParentJob || '无上级岗位' }}</text>
          <image src="/static/arrow_down.png" mode="aspectFit" class="picker-icon"></image>
        </view>
      </view>
      
      <!-- 角色选择 -->
      <view class="form-group">
        <text class="label">角色 <text class="required">*</text></text>
        <view class="picker-field" @click="showRolePicker = true">
          <text class="picker-display">{{ getSelectedRoleText() }}</text>
          <image src="/static/arrow_down.png" mode="aspectFit" class="picker-icon"></image>
        </view>
      </view>
      
      <!-- 备注 -->
      <view class="form-group">
        <text class="label">备注</text>
        <textarea 
          v-model="formData.remark" 
          placeholder="请输入备注信息" 
          class="textarea-field" 
          auto-height 
        ></textarea>
      </view>
      
      <!-- 提交按钮 -->
      <view class="submit-section">
        <button class="submit-btn" @click="submitForm" :loading="submitting">{{ isEditMode ? '保存修改' : '添加岗位' }}</button>
      </view>
    </view>
    
    <!-- 上级岗位选择器 -->
    <picker 
      v-if="showJobPicker" 
      :range="jobOptions" 
      range-key="name" 
      v-model="parentJobIndex" 
      @change="handleParentJobChange" 
      @cancel="showJobPicker = false"
      class="job-picker"
    ></picker>
    
    <!-- 角色选择器 -->
    <picker 
      v-if="showRolePicker" 
      :range="roleOptions" 
      range-key="name" 
      v-model="roleIndex" 
      @change="handleRoleChange" 
      @cancel="showRolePicker = false"
      class="role-picker"
    ></picker>
  </view>
</template>

<script>
export default {
  data() {
    return {
      jobId: '',
      isEditMode: false,
      formData: {
        pid: 0,
        name: '',
        remark: '',
        role: '4',
        rules: '-'
      },
      jobOptions: [],
      parentJobIndex: 0,
      selectedParentJob: '',
      roleOptions: [
        { id: '1', name: '管理员' },
        { id: '2', name: '店长' },
        { id: '3', name: '副店长' },
        { id: '4', name: '员工' }
      ],
      roleIndex: 3,
      showJobPicker: false,
      showRolePicker: false,
      submitting: false,
      allJobs: []
    };
  },
  onLoad(options) {
    if (options.id) {
      this.jobId = options.id;
      this.isEditMode = true;
      // 先获取岗位列表，再获取要编辑的岗位详情
      this.getJobList().then(() => {
        this.getJobInfo();
      });
    } else {
      // 添加模式，只需要获取岗位列表
      this.getJobList();
    }
  },
  methods: {
    // 获取岗位列表
    async getJobList() {
      try {
        const res = await this.$request({
          url: '/job/index',
          method: 'GET'
        });
        
        if (res.code === 1) {
          this.allJobs = res.data;
          // 扁平化岗位列表用于选择器
          this.jobOptions = this.flattenJobs(res.data);
          // 添加一个"无上级岗位"的选项
          this.jobOptions.unshift({ id: 0, name: '无上级岗位' });
        } else {
          throw new Error(res.msg || '获取岗位列表失败');
        }
      } catch (error) {
        console.error('获取岗位列表失败:', error);
        uni.showToast({
          title: error.message || '获取岗位列表失败',
          icon: 'none'
        });
      }
    },
    
    // 扁平化岗位数据
    flattenJobs(jobs) {
      const flatJobs = [];
      
      const flatten = (jobs, level = 0) => {
        jobs.forEach(job => {
          flatJobs.push({
            id: job.id,
            name: ' '.repeat(level * 2) + job.name,
            originalName: job.name
          });
          
          if (job.children && job.children.length > 0) {
            flatten(job.children, level + 1);
          }
        });
      };
      
      flatten(jobs);
      return flatJobs;
    },
    
    // 获取岗位详情（编辑模式）
    async getJobInfo() {
      try {
        const res = await this.$request({
          url: '/job/edit',
          method: 'GET',
          params: {
            ids: this.jobId
          }
        });
        
        if (res.code === 1) {
          const jobInfo = res.data;
          this.formData = {
            pid: jobInfo.pid || 0,
            name: jobInfo.name || '',
            remark: jobInfo.remark || '',
            role: jobInfo.role || '4',
            rules: jobInfo.rules || '-'
          };
          
          // 设置选中的上级岗位
          this.parentJobIndex = this.jobOptions.findIndex(item => item.id === this.formData.pid) || 0;
          this.selectedParentJob = this.parentJobIndex > 0 ? this.jobOptions[this.parentJobIndex].originalName : '';
          
          // 设置选中的角色
          this.roleIndex = this.roleOptions.findIndex(item => item.id === this.formData.role) || 3;
        } else {
          throw new Error(res.msg || '获取岗位详情失败');
        }
      } catch (error) {
        console.error('获取岗位详情失败:', error);
        uni.showToast({
          title: error.message || '获取岗位详情失败',
          icon: 'none'
        });
        // 如果获取失败，返回上一页
        setTimeout(() => {
          uni.navigateBack();
        }, 1500);
      }
    },
    
    // 获取选中的角色文本
    getSelectedRoleText() {
      return this.roleOptions[this.roleIndex]?.name || '员工';
    },
    
    // 处理上级岗位选择
    handleParentJobChange(e) {
      const index = e.detail.value;
      this.parentJobIndex = index;
      const selectedJob = this.jobOptions[index];
      this.formData.pid = selectedJob.id;
      this.selectedParentJob = selectedJob.id === 0 ? '' : selectedJob.originalName;
      this.showJobPicker = false;
    },
    
    // 处理角色选择
    handleRoleChange(e) {
      const index = e.detail.value;
      this.roleIndex = index;
      this.formData.role = this.roleOptions[index].id;
      this.showRolePicker = false;
    },
    
    // 表单验证
    validateForm() {
      if (!this.formData.name.trim()) {
        uni.showToast({ title: '请输入岗位名称', icon: 'none' });
        return false;
      }
      
      if (!this.formData.role) {
        uni.showToast({ title: '请选择角色', icon: 'none' });
        return false;
      }
      
      // 如果是编辑模式，检查是否选择了自己作为上级岗位
      if (this.isEditMode && parseInt(this.formData.pid) === parseInt(this.jobId)) {
        uni.showToast({ title: '不能选择自己作为上级岗位', icon: 'none' });
        return false;
      }
      
      return true;
    },
    
    // 提交表单
    async submitForm() {
      if (!this.validateForm()) {
        return;
      }
      
      try {
        this.submitting = true;
        const url = this.isEditMode ? '/job/edit' : '/job/add';
        const method = 'POST';
        
        const res = await this.$request({
          url,
          method,
          data: {
            ...this.formData,
            // 编辑模式需要传递id
            ...(this.isEditMode && { id: this.jobId })
          }
        });
        
        if (res.code === 1) {
          uni.showToast({
            title: res.msg || (this.isEditMode ? '编辑成功' : '添加成功'),
            icon: 'success'
          });
          
          // 延迟返回上一页，让用户看到成功提示
          setTimeout(() => {
            uni.navigateBack();
          }, 1500);
        } else {
          throw new Error(res.msg || (this.isEditMode ? '编辑失败' : '添加失败'));
        }
      } catch (error) {
        console.error(this.isEditMode ? '编辑岗位失败:' : '添加岗位失败:', error);
        uni.showToast({
          title: error.message || (this.isEditMode ? '编辑失败' : '添加失败'),
          icon: 'none'
        });
      } finally {
        this.submitting = false;
      }
    },
    
    // 返回上一页
    handleBack() {
      // 如果表单有内容，提示用户是否放弃编辑
      if ((this.formData.name || this.formData.remark) && !this.submitting) {
        uni.showModal({
          title: '提示',
          content: '确定要放弃编辑吗？',
          success: (res) => {
            if (res.confirm) {
              uni.navigateBack();
            }
          }
        });
      } else {
        uni.navigateBack();
      }
    }
  }
};
</script>

<style scoped>
.job-edit-container {
  min-height: 100vh;
  background-color: #f8f8f8;
  position: relative;
  z-index: 1;
}

/* 顶部导航栏 */
.top-bar {
  display: flex;
  justify-content: space-between;
  align-items: center;
  padding: 40rpx 30rpx;
  background-color: #fff;
  box-shadow: 0 2rpx 10rpx rgba(0, 0, 0, 0.05);
  position: relative;
}

.back-btn {
  width: 44rpx;
  height: 44rpx;
  display: flex;
  align-items: center;
  justify-content: center;
}

.back-icon {
  width: 24rpx;
  height: 40rpx;
}

.title {
  font-size: 36rpx;
  font-weight: bold;
  color: #333;
  position: absolute;
  left: 50%;
  top: 50%;
  transform: translate(-50%, -50%);
}

.right-space {
  width: 44rpx;
}

/* 表单容器 */
.form-container {
  padding: 30rpx;
  position: relative;
  z-index: 10;
}

/* 表单组 */
.form-group {
  background-color: #fff;
  margin-bottom: 30rpx;
  border-radius: 15rpx;
  padding: 30rpx;
  box-shadow: 0 2rpx 10rpx rgba(0, 0, 0, 0.05);
  position: relative;
  z-index: 20;
}

.label {
  display: block;
  font-size: 28rpx;
  color: #333;
  margin-bottom: 20rpx;
}

.required {
  color: #ff3b30;
}

/* 输入框 */
.input-field {
  width: 100%;
  padding: 20rpx;
  border: 1rpx solid #ddd;
  border-radius: 10rpx;
  font-size: 28rpx;
  box-sizing: border-box;
  background-color: #fff;
  pointer-events: auto;
  z-index: 1;
  height: 84rpx;
}

/* 文本域 */
.textarea-field {
  width: 100%;
  min-height: 150rpx;
  padding: 20rpx;
  border: 1rpx solid #ddd;
  border-radius: 10rpx;
  font-size: 28rpx;
  box-sizing: border-box;
  background-color: #fff;
}

/* 选择器字段 */
.picker-field {
  display: flex;
  justify-content: space-between;
  align-items: center;
  padding: 20rpx;
  border: 1rpx solid #ddd;
  border-radius: 10rpx;
  background-color: #fff;
  pointer-events: auto;
  position: relative;
  z-index: 20;
}

.picker-display {
  font-size: 28rpx;
  color: #666;
  background-color: #fff;
}

.picker-icon {
  width: 24rpx;
  height: 24rpx;
}

/* 提交按钮 */
.submit-section {
  padding: 30rpx 0;
}

.submit-btn {
  width: 100%;
  padding: 28rpx 0;
  background-color: #4cd964;
  color: #fff;
  border: none;
  border-radius: 15rpx;
  font-size: 32rpx;
  font-weight: bold;
}

/* 选择器样式 */
.job-picker,
.role-picker {
  position: fixed;
  bottom: 0;
  left: 0;
  right: 0;
  background-color: #fff;
  z-index: 999;
}
</style>